<template>
  <div>
    <!-- immediate-check 初始化时立即执行滚动位置检查 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :immediate-check="false" offset="50">
        <ArticleItem v-for="obj in channelList" :key="obj.art_id" :artObj="obj" @dislikeEV="dislikeFn" @reportEv="reportFn" @click.native="itemClickFn(obj.art_id)"></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '../../../components/ArticleItem.vue'
import { getAllArticleList, dislikeArticle, reportArticleApi } from '@/api'
import { Toast } from 'vant'
export default {
  props: {
    list: Number // 频道ID
  },
  data() {
    return {
      channelList: [], // 文章列表
      loading: false, // 加载中状态
      finished: false, // 完成加载状态
      theTime: (new Date()).getTime(), // 用于请求下一页的时间戳 getTime()获取时间戳
      isLoading: false // 顶部刷新的状态
    }
  },
  components: {
    ArticleItem
  },
  async created() {
    this.getAllArticleListFn()
  },
  methods: {
    // 统一封装获取文章列表的方法
    async getAllArticleListFn() {
      const res = await getAllArticleList({
        channel_id: this.list, // 频道的id
        timestamp: this.theTime
      })
      this.theTime = res.data.data.pre_timestamp
      this.channelList = [...this.channelList, ...res.data.data.results]
      this.loading = false // 数据更新加载完毕 loading 设为false
      // 数据全部加载完毕
      if (res.data.data.pre_timestamp === null) {
        this.finished = true
      }
      // 上拉刷新加载完成
      this.isLoading = false
    },
    // 底部加载更多的回调
    async onLoad() {
      if (this.channelList.length === 0) { // 防止在created的res还没回来之前  onLoad再发一次请求 导致上来就发两次请求(key重复报错)
        return
      }
      this.getAllArticleListFn()
    },
    // 顶部上拉刷新的回调
    async onRefresh() {
      this.channelList = []
      this.theTime = (new Date()).getTime()
      this.getAllArticleListFn()
    },
    // 不感兴趣的回调
    async dislikeFn(artID) {
      await dislikeArticle(artID)
      // 反馈成功
      Toast('反馈成功')
    },
    // 举报垃圾内容的回调
    async reportFn(artID, type) {
      await reportArticleApi({ artID, type })
      Toast('反馈成功')
    },
    // 文章每个列表的点击事件
    itemClickFn(id) { // 事件修饰符.native -> 给组件内根标签绑定原生的click点击事件
      // 跳转到文章详情页并携带文章id
      this.$router.push(`/detail?art_id=${id}`)
    }
  }
}
</script>

<style>
</style>
